package com.zdkj.subway.stm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.common.core.constant.CommonConstants;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.stm.constant.StmTableCommon;
import com.zdkj.subway.stm.dto.in.SwStTvmCheckDetailDTO;
import com.zdkj.subway.stm.entity.*;
import com.zdkj.subway.stm.mapper.SwStTvmCheckDetailMapper;
import com.zdkj.subway.stm.service.*;
import com.zdkj.subway.stm.util.BeanUtilsStm;
import com.zdkj.subway.stm.util.DateUtilStm;
import com.zdkj.subway.stm.util.JdbcUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * TVM详细日清点表（主表）
 *
 * @author songtuo
 * @date 2020-03-05 21:04:12
 */
@Service
@Slf4j
@AllArgsConstructor
public class SwStTvmCheckDetailServiceImpl extends ServiceImpl<SwStTvmCheckDetailMapper, SwStTvmCheckDetail> implements SwStTvmCheckDetailService {
    @Autowired
    SwStTvmCheckDetailCoinChangeService swStTvmCheckDetailCoinChangeService;
    @Autowired
    SwStTvmCheckDetailCoinService swStTvmCheckDetailCoinService;
    @Autowired
    SwStTvmCheckDetailPaperService swStTvmCheckDetailPaperService;
    @Autowired
    SwStTvmCheckDetailPaperChangeService swStTvmCheckDetailPaperChangeService;
    @Autowired
    SwStTvmCheckDetailWasteService stTvmCheckDetailWasteService;
    @Resource
    SwStTvmCheckDetailMapper swStTvmCheckDetailMapper;
    @Autowired
    SwStInputCashboxUninstalledService uninstalledService;
    @Autowired
    SwStInputCashboxUninstalledService swStInputCashboxUninstalledService;

    private final SwStmStationDataEntryLogService swStmStationDataEntryLogService;

    @Override
    @Transactional
    public boolean saveSwStTvmCheckDetail(SwStTvmCheckDetailDTO swStTvmCheckDetailDTO) {
        log.info("save data time {} dto:{}", LocalDateTime.now(), JSON.toJSONString(swStTvmCheckDetailDTO));
        // 当前的主表没有加强外键 假如加强外键的情况下必须先插入主表
        SwStTvmCheckDetail swStTvmCheckDetail = swStTvmCheckDetailDTO.getSwStTvmCheckDetail();
        SwStTvmCheckDetail swStTvmCheckDetailObj = ObjectUtils.getDefaultObj(SwStTvmCheckDetail.class);
        BeanUtil.copyProperties(swStTvmCheckDetailObj, swStTvmCheckDetail, CopyOptions.create().setIgnoreNullValue(true));
        //1:支持前台自己传入清点时间 如果前台没有传清点时间那么后台自己为前台生成一个  避免系统异常的情况下 用户手动录入
        if (swStTvmCheckDetail.getCheckTime() == null) {
            swStTvmCheckDetail.setCheckTime(DateUtilStm.localDateToString(LocalDate.now()));
            swStTvmCheckDetail.setRevenueTime(LocalDate.now());
        }
        //2:为所有的钱箱复制 创建人名称 创建人Id 部门Id 创建时间 删除标志等等
        List<SwStTvmCheckDetailCoinChange> swStTvmCoinChanges = swStTvmCheckDetailDTO.getSwStTvmCheckDetailCoinChanges();
        BeanUtilsStm.buildProperties(swStTvmCoinChanges);
        List<SwStTvmCheckDetailCoin> swStTvmCoins = swStTvmCheckDetailDTO.getSwStTvmCheckDetailCoins();
        BeanUtilsStm.buildProperties(swStTvmCoins);
        List<SwStTvmCheckDetailPaperChange> swStTvmPaperChanges = swStTvmCheckDetailDTO.getSwStTvmCheckDetailPaperChanges();
        BeanUtilsStm.buildProperties(swStTvmPaperChanges);
        List<SwStTvmCheckDetailPaper> swStTvmPapers = swStTvmCheckDetailDTO.getSwStTvmCheckDetailPapers();
        BeanUtilsStm.buildProperties(swStTvmPapers);
        List<SwStTvmCheckDetailWaste> swStTvmWastes = swStTvmCheckDetailDTO.getSwStTvmCheckDetailWastes();
        BeanUtilsStm.buildProperties(swStTvmWastes);
        //3:对所有的钱箱进行汇总计算  主表中的清点金额等于所有从表中的实点金额的一个总和  注意按照TVM级别进程分层统计
        Map<String, Double> realCountMap = getAllRealCount(swStTvmCoinChanges, swStTvmCoins, swStTvmPaperChanges, swStTvmPapers, swStTvmWastes);
        //4:保存主表  注意主表可能也是多条数据 按照Tvm编号进行更新数据
        Map<String, Integer> relationIdsMap = saveSwStTvmCheckDetails(realCountMap, swStTvmCheckDetail);
        //5:保存从表
        saveSwStTvmCheckDetailsSun(swStTvmCoinChanges, swStTvmCoins, swStTvmPaperChanges, swStTvmPapers, swStTvmWastes, relationIdsMap);
        //6: 同步钱箱未卸载数据 verision  7.7
        synCashBoxUninstallData(swStTvmCheckDetail, swStTvmCoinChanges, swStTvmCoins, swStTvmPaperChanges, swStTvmPapers, swStTvmWastes);
        return true;
    }

    /**
     * 同步钱箱未卸载数据
     *
     * @param sw
     * @param swStTvmCoinChanges
     * @param swStTvmCoins
     * @param swStTvmPaperChanges
     * @param swStTvmPapers
     * @param swStTvmWastes
     */
    private void synCashBoxUninstallData(SwStTvmCheckDetail sw, List<SwStTvmCheckDetailCoinChange> swStTvmCoinChanges, List<SwStTvmCheckDetailCoin> swStTvmCoins, List<SwStTvmCheckDetailPaperChange> swStTvmPaperChanges, List<SwStTvmCheckDetailPaper> swStTvmPapers, List<SwStTvmCheckDetailWaste> swStTvmWastes) {
        List<SwStInputCashboxUninstalled> uninstalleds = new ArrayList<>();
        //1:分别从五个钱箱中统计出来 所有的未卸载的数据  然后同步到未卸载的表里面
        if (CollectionUtil.isNotEmpty(swStTvmCoinChanges)) {
            List<SwStTvmCheckDetailCoinChange> filterData = swStTvmCoinChanges.stream().filter(x -> x.getUnloadStatus() == 1).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(filterData)) {
                for (SwStTvmCheckDetailCoinChange c : filterData) {
                    SwStInputCashboxUninstalled build = SwStInputCashboxUninstalled.builder().checkPersonName(sw.getCheckPersonOneName()).remark(sw.getRemark()).lineCode(sw.getLineCode()).stationCode(sw.getStationCode())
                            .isSubmit("0").inventoryPersonJobNo(sw.getCheckPersonOneJopNo()).inventoryPersonId(sw.getCheckPersonOneId()).tvmCode(c.getTvmCode())
                            .uninstalledDate(DateUtilStm.stringTolocalDate(sw.getCheckTime())).shouldBeUnloadedAmount(c.getSysAmount()).uninstallAmount(c.getRealAmount()).differenceAmount(c.getDiffAmount())
                            .moneyBoxType("2").build();
                            //.moneyBoxCode(c.getCashboxCode()).moneyBoxType("2").build();
                    build.setCreateTime(LocalDateTime.now());
                    build.setCreatorId(sw.getCreatorId());
                    build.setCreatorName(sw.getCreatorName());
                    build.setDelFlag("0");
                    build.setDeptId(sw.getDeptId());
                    uninstalleds.add(build);
                }
            }
        }
        if (CollectionUtil.isNotEmpty(swStTvmCoins)) {
            List<SwStTvmCheckDetailCoin> filterData = swStTvmCoins.stream().filter(x -> x.getUnloadStatus() == 1).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(filterData)) {
                for (SwStTvmCheckDetailCoin c : filterData) {
                    SwStInputCashboxUninstalled build = SwStInputCashboxUninstalled.builder().checkPersonName(sw.getCheckPersonOneName())
                            .remark(sw.getRemark()).lineCode(sw.getLineCode()).stationCode(sw.getStationCode())
                            .isSubmit("0").inventoryPersonJobNo(sw.getCheckPersonOneJopNo()).inventoryPersonId(sw.getCheckPersonOneId()).tvmCode(c.getTvmCode())
                            .uninstalledDate(DateUtilStm.stringTolocalDate(sw.getCheckTime())).shouldBeUnloadedAmount(c.getSysAmount()).uninstallAmount(c.getRealAmount()).differenceAmount(c.getDiffAmount())
                            .moneyBoxType("1").build();
                            //.moneyBoxCode(c.getCashboxCode()).moneyBoxType("1").build();
                    build.setCreateTime(LocalDateTime.now());
                    build.setCreatorId(sw.getCreatorId());
                    build.setCreatorName(sw.getCreatorName());
                    build.setDelFlag("0");
                    build.setDeptId(sw.getDeptId());

                    uninstalleds.add(build);
                }
            }
        }
        if (CollectionUtil.isNotEmpty(swStTvmPaperChanges)) {
            List<SwStTvmCheckDetailPaperChange> filterData = swStTvmPaperChanges.stream().filter(x -> x.getUnloadStatus() == 1).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(filterData)) {
                for (SwStTvmCheckDetailPaperChange c : filterData) {
                    SwStInputCashboxUninstalled build = SwStInputCashboxUninstalled.builder().checkPersonName(sw.getCheckPersonOneName())
                            .remark(sw.getRemark()).lineCode(sw.getLineCode()).stationCode(sw.getStationCode())
                            .isSubmit("0").inventoryPersonJobNo(sw.getCheckPersonOneJopNo()).inventoryPersonId(sw.getCheckPersonOneId()).tvmCode(c.getTvmCode())
                            .uninstalledDate(DateUtilStm.stringTolocalDate(sw.getCheckTime())).shouldBeUnloadedAmount(c.getSysAmount()).uninstallAmount(c.getRealAmount()).differenceAmount(c.getDiffAmount())
                            .moneyBoxType("4").nsAmount(c.getNsAmount()).build();
                            //.moneyBoxCode(c.getCashboxCode()).moneyBoxType("4").nsAmount(c.getNsAmount()).build();
                    build.setCreateTime(LocalDateTime.now());
                    build.setCreatorId(sw.getCreatorId());
                    build.setCreatorName(sw.getCreatorName());
                    build.setDelFlag("0");
                    build.setDeptId(sw.getDeptId());
                    uninstalleds.add(build);
                }
            }
        }
        if (CollectionUtil.isNotEmpty(swStTvmPapers)) {
            List<SwStTvmCheckDetailPaper> filterData = swStTvmPapers.stream().filter(x -> x.getUnloadStatus() == 1).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(filterData)) {
                for (SwStTvmCheckDetailPaper c : filterData) {
                    SwStInputCashboxUninstalled build = SwStInputCashboxUninstalled.builder().checkPersonName(sw.getCheckPersonOneName())
                            .remark(sw.getRemark()).lineCode(sw.getLineCode()).stationCode(sw.getStationCode())
                            .isSubmit("0").inventoryPersonJobNo(sw.getCheckPersonOneJopNo()).inventoryPersonId(sw.getCheckPersonOneId()).tvmCode(c.getTvmCode())
                            .uninstalledDate(DateUtilStm.stringTolocalDate(sw.getCheckTime())).shouldBeUnloadedAmount(c.getSysAmount()).uninstallAmount(c.getRealAmount()).differenceAmount(c.getDiffAmount())
                            .moneyBoxType("3").nsAmount(c.getNsAmount()).build();
                            //.moneyBoxCode(c.getCashboxCode()).moneyBoxType("3").nsAmount(c.getNsAmount()).build();
                    build.setCreateTime(LocalDateTime.now());
                    build.setCreatorId(sw.getCreatorId());
                    build.setCreatorName(sw.getCreatorName());
                    build.setDelFlag("0");
                    build.setDeptId(sw.getDeptId());
                    uninstalleds.add(build);
                }
            }
        }
        if (CollectionUtil.isNotEmpty(swStTvmWastes)) {
            List<SwStTvmCheckDetailWaste> filterData = swStTvmWastes.stream().filter(x -> x.getUnloadStatus() == 1).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(filterData)) {
                for (SwStTvmCheckDetailWaste c : filterData) {
                    SwStInputCashboxUninstalled build = SwStInputCashboxUninstalled.builder().checkPersonName(sw.getCheckPersonOneName())
                            .remark(sw.getRemark()).lineCode(sw.getLineCode()).stationCode(sw.getStationCode())
                            .isSubmit("0").inventoryPersonJobNo(sw.getCheckPersonOneJopNo()).inventoryPersonId(sw.getCheckPersonOneId()).tvmCode(c.getTvmCode())
                            .uninstalledDate(DateUtilStm.stringTolocalDate(sw.getCheckTime())).shouldBeUnloadedAmount(c.getSysAmount()).uninstallAmount(c.getRealAmount()).differenceAmount(c.getDiffAmount())
                            .moneyBoxType("5").nsAmount(c.getNsAmount()).build();
                            //.moneyBoxCode(c.getCashboxCode()).moneyBoxType("5").nsAmount(c.getNsAmount()).build();
                    build.setCreateTime(LocalDateTime.now());
                    build.setCreatorId(sw.getCreatorId());
                    build.setCreatorName(sw.getCreatorName());
                    build.setDelFlag("0");
                    build.setDeptId(sw.getDeptId());
                    uninstalleds.add(build);
                }
            }
        }
        //同步添加 未卸载的数据 解决重复添加的问题
        if (CollectionUtil.isNotEmpty(uninstalleds)) {
            Iterator<SwStInputCashboxUninstalled> it = uninstalleds.iterator();
            while (it.hasNext()) {
                SwStInputCashboxUninstalled uninstalled = it.next();
                SwStInputCashboxUninstalled one = uninstalledService.getOne(new QueryWrapper<SwStInputCashboxUninstalled>().lambda().eq(SwStInputCashboxUninstalled::getLineCode, uninstalled.getLineCode())
                        .eq(SwStInputCashboxUninstalled::getStationCode, uninstalled.getStationCode()).eq(SwStInputCashboxUninstalled::getTvmCode, uninstalled.getTvmCode())
                        .eq(SwStInputCashboxUninstalled::getMoneyBoxType, uninstalled.getMoneyBoxType()).eq(SwStInputCashboxUninstalled::getMoneyBoxCode, uninstalled.getMoneyBoxCode())
                        .eq(SwStInputCashboxUninstalled::getUninstalledDate, uninstalled.getUninstalledDate()));
                if (one != null) {
                    it.remove();
                }
            }
            uninstalledService.saveBatch(uninstalleds);
        }
    }

    /**
     * 保存每个从表的数据
     *
     * @param swStTvmCoinChanges
     * @param swStTvmCoins
     * @param swStTvmPaperChanges
     * @param swStTvmPapers
     * @param swStTvmWastes
     * @param relationIdsMap
     */
    private void saveSwStTvmCheckDetailsSun(List<SwStTvmCheckDetailCoinChange> swStTvmCoinChanges,
                                            List<SwStTvmCheckDetailCoin> swStTvmCoins, List<SwStTvmCheckDetailPaperChange>
                                                    swStTvmPaperChanges, List<SwStTvmCheckDetailPaper> swStTvmPapers,
                                            List<SwStTvmCheckDetailWaste> swStTvmWastes, Map<String, Integer> relationIdsMap) {
        //1:为从表的每一条记录设置外键Id
        if (CollectionUtil.isNotEmpty(swStTvmCoinChanges)) {
            for (SwStTvmCheckDetailCoinChange swStTvmCoinChange : swStTvmCoinChanges) {
                //swStTvmCoinChange.setCashboxCode(BeanUtilsStm.strRemoveBlank(swStTvmCoinChange.getCashboxCode()));
                swStTvmCoinChange.setRelationId(relationIdsMap.get(swStTvmCoinChange.getTvmCode()));
            }
            swStTvmCheckDetailCoinChangeService.saveBatch(swStTvmCoinChanges);
        }
        if (CollectionUtil.isNotEmpty(swStTvmCoins)) {
            for (SwStTvmCheckDetailCoin swStTvmCoin : swStTvmCoins) {
                //swStTvmCoin.setCashboxCode(BeanUtilsStm.strRemoveBlank(swStTvmCoin.getCashboxCode()));
                swStTvmCoin.setRelationId(relationIdsMap.get(swStTvmCoin.getTvmCode()));
            }
            swStTvmCheckDetailCoinService.saveBatch(swStTvmCoins);
        }
        if (CollectionUtil.isNotEmpty(swStTvmPaperChanges)) {
            for (SwStTvmCheckDetailPaperChange swStTvmPaperChange : swStTvmPaperChanges) {
                //swStTvmPaperChange.setCashboxCode(BeanUtilsStm.strRemoveBlank(swStTvmPaperChange.getCashboxCode()));
                swStTvmPaperChange.setRelationId(relationIdsMap.get(swStTvmPaperChange.getTvmCode()));
            }
            swStTvmCheckDetailPaperChangeService.saveBatch(swStTvmPaperChanges);
        }
        if (CollectionUtil.isNotEmpty(swStTvmPapers)) {
            for (SwStTvmCheckDetailPaper swStTvmPaper : swStTvmPapers) {
                //swStTvmPaper.setCashboxCode(BeanUtilsStm.strRemoveBlank(swStTvmPaper.getCashboxCode()));
                swStTvmPaper.setRelationId(relationIdsMap.get(swStTvmPaper.getTvmCode()));
            }
            swStTvmCheckDetailPaperService.saveBatch(swStTvmPapers);
        }
        if (CollectionUtil.isNotEmpty(swStTvmWastes)) {
            for (SwStTvmCheckDetailWaste swStTvmWast : swStTvmWastes) {
                //swStTvmWast.setCashboxCode(BeanUtilsStm.strRemoveBlank(swStTvmWast.getCashboxCode()));
                swStTvmWast.setRelationId(relationIdsMap.get(swStTvmWast.getTvmCode()));
            }
            stTvmCheckDetailWasteService.saveBatch(swStTvmWastes);
        }
    }

    /**
     * 保存Tvm编号
     *
     * @param map key是tvm value是实际清点的数据
     * @return
     */
    private Map<String, Integer> saveSwStTvmCheckDetails(Map<String, Double> map, SwStTvmCheckDetail swStTvmCheckDetail) {
        Map<String, Integer> relationIdsMap = new HashMap<>();
        Set<String> tvmCodes = map.keySet();
        for (String tvmCode : tvmCodes) {
            SwStTvmCheckDetail sw = new SwStTvmCheckDetail();
            sw.setTvmCode(tvmCode);
            if (map.get(tvmCode) != null) {
                sw.setCheckAmount(new BigDecimal(map.get(tvmCode)));
            }
            //将主表中的其他数据存储新建的tvm当中
            BeanUtil.copyProperties(swStTvmCheckDetail, sw, CopyOptions.create().setIgnoreNullValue(true));
            save(sw);
            relationIdsMap.put(sw.getTvmCode(), sw.getId());
        }
        return relationIdsMap;
    }

    /**
     * 获取清点的总金额优化方向 <List?extends 父类方式方式> 由于已经继承了model暂时先不用
     *
     * @param swStTvmCoinChanges
     * @param swStTvmCoins
     * @param swStTvmPaperChanges
     * @param swStTvmPapers
     * @param swStTvmWastes
     * @return
     */
    private Map<String, Double> getAllRealCount(List<SwStTvmCheckDetailCoinChange> swStTvmCoinChanges, List<SwStTvmCheckDetailCoin> swStTvmCoins,
                                                List<SwStTvmCheckDetailPaperChange> swStTvmPaperChanges, List<SwStTvmCheckDetailPaper> swStTvmPapers,
                                                List<SwStTvmCheckDetailWaste> swStTvmWastes) {
        Map<String, Double> realCountMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(swStTvmCoinChanges)) {
            for (SwStTvmCheckDetailCoinChange swStTvmCoinChange : swStTvmCoinChanges) {
                BigDecimal realAmount = swStTvmCoinChange.getRealAmount();
                String tvmCode = swStTvmCoinChange.getTvmCode();
                if (swStTvmCoinChange.getUnloadStatus() == null) {
                    swStTvmCoinChange.setUnloadStatus(0);
                }
                if (swStTvmCoinChange.getUnloadStatus() != 1) {
                    countRealAmountByTvmCode(realCountMap, realAmount, tvmCode);
                } else {
                    if (!realCountMap.containsKey(tvmCode)) {
                        realCountMap.put(tvmCode, 0d);
                    }
                }
            }
        }
        if (CollectionUtil.isNotEmpty(swStTvmCoins)) {
            for (SwStTvmCheckDetailCoin swStTvmCoin : swStTvmCoins) {
                BigDecimal realAmount = swStTvmCoin.getRealAmount();
                String tvmCode = swStTvmCoin.getTvmCode();
                if (swStTvmCoin.getUnloadStatus() == null) {
                    swStTvmCoin.setUnloadStatus(0);
                }
                if (swStTvmCoin.getUnloadStatus() != 1) {
                    countRealAmountByTvmCode(realCountMap, realAmount, tvmCode);
                } else {
                    if (!realCountMap.containsKey(tvmCode)) {
                        realCountMap.put(tvmCode, 0d);
                    }
                }
            }
        }
        if (CollectionUtil.isNotEmpty(swStTvmPaperChanges)) {
            for (SwStTvmCheckDetailPaperChange swStTvmPaperChange : swStTvmPaperChanges) {
                BigDecimal realAmount = swStTvmPaperChange.getRealAmount();
                String tvmCode = swStTvmPaperChange.getTvmCode();
                if (swStTvmPaperChange.getUnloadStatus() == null) {
                    swStTvmPaperChange.setUnloadStatus(0);
                }
                if (swStTvmPaperChange.getUnloadStatus() != 1) {
                    countRealAmountByTvmCode(realCountMap, realAmount, tvmCode);
                } else {
                    if (!realCountMap.containsKey(tvmCode)) {
                        realCountMap.put(tvmCode, 0d);
                    }
                }
            }
        }
        if (CollectionUtil.isNotEmpty(swStTvmPapers)) {
            for (SwStTvmCheckDetailPaper swStTvmPaper : swStTvmPapers) {
                BigDecimal realAmount = swStTvmPaper.getRealAmount();
                String tvmCode = swStTvmPaper.getTvmCode();
                if (swStTvmPaper.getUnloadStatus() == null) {
                    swStTvmPaper.setUnloadStatus(0);
                }
                if (swStTvmPaper.getUnloadStatus() != 1) {
                    countRealAmountByTvmCode(realCountMap, realAmount, tvmCode);
                } else {
                    if (!realCountMap.containsKey(tvmCode)) {
                        realCountMap.put(tvmCode, 0d);
                    }
                }
            }
        }
        if (CollectionUtil.isNotEmpty(swStTvmWastes)) {
            for (SwStTvmCheckDetailWaste swStTvmWaste : swStTvmWastes) {
                BigDecimal realAmount = swStTvmWaste.getRealAmount();
                String tvmCode = swStTvmWaste.getTvmCode();
                if (swStTvmWaste.getUnloadStatus() == null) {
                    swStTvmWaste.setUnloadStatus(0);
                }
                if (swStTvmWaste.getUnloadStatus() != 1) {
                    countRealAmountByTvmCode(realCountMap, realAmount, tvmCode);
                } else {
                    //未卸载的钱箱也应该有一张主表
                    if (!realCountMap.containsKey(tvmCode)) {
                        realCountMap.put(tvmCode, 0d);
                    }
                }
            }
        }
        return realCountMap;
    }

    /**
     * 统计 每个Tvm的钱数 通过Tvm  code
     *
     * @param realCountMap key 是tvm code 的key值  value 是具体的钱数
     * @param realAmount
     * @param tvmCode
     */
    private void countRealAmountByTvmCode(Map<String, Double> realCountMap, BigDecimal realAmount, String tvmCode) {
        if (StringUtils.isEmpty(tvmCode)) {
            return;
        }
        if (realAmount != null) {
            if (realCountMap.get(tvmCode) != null) {
                realCountMap.put(tvmCode, realCountMap.get(tvmCode) + realAmount.doubleValue());
            } else {
                realCountMap.put(tvmCode, realAmount.doubleValue());
            }
        } else {
            if (!realCountMap.containsKey(tvmCode)) {
                realCountMap.put(tvmCode, 0d);
            }
        }
    }

    /**
     * 更新数据 更新的时候一般情况下是一条数据
     *
     * @param swStTvmCheckDetailDTO 数据更新dto
     * @return
     */
    @Override
    @Transactional
    public boolean updateSwStTvmCheckDetail(SwStTvmCheckDetailDTO swStTvmCheckDetailDTO) {
        log.info("save data time {} dto:{}", LocalDateTime.now(), JSON.toJSONString(swStTvmCheckDetailDTO));
        SwStTvmCheckDetail swStTvmCheckDetail = swStTvmCheckDetailDTO.getSwStTvmCheckDetail();
        swStTvmCheckDetail.setConfirmStatus("0");
        String tvmCode = swStTvmCheckDetail.getTvmCode();
        Integer rid = swStTvmCheckDetail.getId();


        //1:更新从表的数据  注意更新的时候有新增 和删除的场景 需要在这里搞一搞  比如后期编辑的时候需要新增数据或者删除数据 这里应该都支持
        List<SwStTvmCheckDetailCoinChange> swStTvmCheckDetailCoinChanges = swStTvmCheckDetailDTO.getSwStTvmCheckDetailCoinChanges();
        if (CollectionUtil.isNotEmpty(swStTvmCheckDetailCoinChanges)) {
            // 维护一种复杂场景 更新过程中 如果新增或者删除的场景的话 比如 后期又突然增加钱箱号
            updateCoinChangeData(swStTvmCheckDetailDTO,rid, swStTvmCheckDetailCoinChanges);
        }
        List<SwStTvmCheckDetailCoin> swStTvmCheckDetailCoins = swStTvmCheckDetailDTO.getSwStTvmCheckDetailCoins();
        if (CollectionUtil.isNotEmpty(swStTvmCheckDetailCoins)) {
            updateCoinData(swStTvmCheckDetailDTO,rid, swStTvmCheckDetailCoins);
        }
        List<SwStTvmCheckDetailPaper> swStTvmCheckDetailPapers = swStTvmCheckDetailDTO.getSwStTvmCheckDetailPapers();
        if (CollectionUtil.isNotEmpty(swStTvmCheckDetailPapers)) {
            updatePaperData(swStTvmCheckDetailDTO, rid, swStTvmCheckDetailPapers);

        }
        List<SwStTvmCheckDetailPaperChange> swStTvmCheckDetailPaperChanges = swStTvmCheckDetailDTO.getSwStTvmCheckDetailPaperChanges();
        if (CollectionUtil.isNotEmpty(swStTvmCheckDetailPaperChanges)) {
            updatePaperChangeData(swStTvmCheckDetailDTO,rid, swStTvmCheckDetailPaperChanges);
        }

        List<SwStTvmCheckDetailWaste> swStTvmCheckDetailWastes = swStTvmCheckDetailDTO.getSwStTvmCheckDetailWastes();
        if (CollectionUtil.isNotEmpty(swStTvmCheckDetailWastes)) {
            updateWasteData(swStTvmCheckDetailDTO, rid, swStTvmCheckDetailWastes);
        }
        //2:更细主表的数据 这里的话主表应该只有一条数据
        Map<String, Double> realCountMap = getAllRealCount(swStTvmCheckDetailCoinChanges, swStTvmCheckDetailCoins, swStTvmCheckDetailPaperChanges, swStTvmCheckDetailPapers, swStTvmCheckDetailWastes);
        if (realCountMap.get(tvmCode) != null) {
            if (realCountMap.get(tvmCode) != null) {
                swStTvmCheckDetail.setCheckAmount(new BigDecimal(realCountMap.get(tvmCode)));
            }
            updateById(swStTvmCheckDetail);
        }
        //同步钱箱未卸载数据
        synCashBoxUninstallData(swStTvmCheckDetail, swStTvmCheckDetailCoinChanges, swStTvmCheckDetailCoins, swStTvmCheckDetailPaperChanges, swStTvmCheckDetailPapers, swStTvmCheckDetailWastes);
        return true;
    }

    /**
     * 更新waste数据 注意这里支持 更新的时候时候新增或者删除 废票
     * @param rid
     * @param swStTvmCheckDetailWastes
     */
    private void updateWasteData(SwStTvmCheckDetailDTO swStTvmCheckDetailDTO, Integer rid, List<SwStTvmCheckDetailWaste> swStTvmCheckDetailWastes) {
        swStTvmCheckDetailWastes.forEach(x -> {
            x.setRelationId(rid);
            //x.setCashboxCode(BeanUtilsStm.strRemoveBlank(x.getCashboxCode()));
        });
        SwStTvmCheckDetail swStTvmCheckDetail =   swStTvmCheckDetailDTO.getSwStTvmCheckDetail();
        List<Integer> wIds = swStTvmCheckDetailWastes.stream().map(SwStTvmCheckDetailWaste::getId).collect(Collectors.toList());
        List<SwStTvmCheckDetailWaste> wList = stTvmCheckDetailWasteService.list(new QueryWrapper<SwStTvmCheckDetailWaste>().lambda().eq(SwStTvmCheckDetailWaste::getRelationId, rid));
        List<Integer> orginWIds = wList.stream().map(SwStTvmCheckDetailWaste::getId).collect(Collectors.toList());
        Collection<Integer> removeWIds = CollectionUtils.subtract(orginWIds, wIds);
        if (CollectionUtils.isNotEmpty(removeWIds)) {
            stTvmCheckDetailWasteService.removeByIds(removeWIds);
        }
        List<SwStTvmCheckDetailWaste> haveTvm = stTvmCheckDetailWasteService.list(new QueryWrapper<SwStTvmCheckDetailWaste>().lambda().eq(SwStTvmCheckDetailWaste::getRelationId, rid).eq(SwStTvmCheckDetailWaste::getTvmCode, swStTvmCheckDetail.getTvmCode()));
        if(CollectionUtil.isNotEmpty(haveTvm)){
            stTvmCheckDetailWasteService.updateBatchById(swStTvmCheckDetailWastes);
        }else{
            stTvmCheckDetailWasteService.saveBatch(swStTvmCheckDetailWastes);
        }
        //stTvmCheckDetailWasteService.saveOrUpdateBatch(swStTvmCheckDetailWastes);
    }

    /**
     * 纸币找零箱 更新  更新的时候兼容 新增数据 和删除数据
     * @param rid
     * @param swStTvmCheckDetailPaperChanges
     */
    private void updatePaperChangeData(SwStTvmCheckDetailDTO swStTvmCheckDetailDTO, Integer rid, List<SwStTvmCheckDetailPaperChange> swStTvmCheckDetailPaperChanges) {
        swStTvmCheckDetailPaperChanges.forEach(x -> {
            x.setRelationId(rid);
            //x.setCashboxCode(BeanUtilsStm.strRemoveBlank(x.getCashboxCode()));
        });
        SwStTvmCheckDetail swStTvmCheckDetail =   swStTvmCheckDetailDTO.getSwStTvmCheckDetail();
        List<Integer> wIds = swStTvmCheckDetailPaperChanges.stream().map(SwStTvmCheckDetailPaperChange::getId).collect(Collectors.toList());
        List<SwStTvmCheckDetailPaperChange> wList = swStTvmCheckDetailPaperChangeService.list(new QueryWrapper<SwStTvmCheckDetailPaperChange>().lambda().eq(SwStTvmCheckDetailPaperChange::getRelationId, rid));
        List<Integer> orginWIds = wList.stream().map(SwStTvmCheckDetailPaperChange::getId).collect(Collectors.toList());
        Collection<Integer> removeWIds = CollectionUtils.subtract(orginWIds, wIds);
        if (CollectionUtils.isNotEmpty(removeWIds)) {
            swStTvmCheckDetailPaperChangeService.removeByIds(removeWIds);
        }
        List<SwStTvmCheckDetailPaperChange> haveTvm = swStTvmCheckDetailPaperChangeService.list(new QueryWrapper<SwStTvmCheckDetailPaperChange>().lambda().eq(SwStTvmCheckDetailPaperChange::getRelationId, rid).eq(SwStTvmCheckDetailPaperChange::getTvmCode, swStTvmCheckDetail.getTvmCode()));
        if(CollectionUtil.isNotEmpty(haveTvm)){
            swStTvmCheckDetailPaperChangeService.updateBatchById(swStTvmCheckDetailPaperChanges);
        }else{
            swStTvmCheckDetailPaperChangeService.saveBatch(swStTvmCheckDetailPaperChanges);
        }
        //swStTvmCheckDetailPaperChangeService.saveOrUpdateBatch(swStTvmCheckDetailPaperChanges);
    }

    /**
     * 更新纸币回收箱
     * @param swStTvmCheckDetailDTO
     * @param rid
     * @param swStTvmCheckDetailPapers
     */
    private void updatePaperData(SwStTvmCheckDetailDTO swStTvmCheckDetailDTO, Integer rid, List<SwStTvmCheckDetailPaper> swStTvmCheckDetailPapers) {
        swStTvmCheckDetailPapers.forEach(x -> {
            x.setRelationId(rid);
            //x.setCashboxCode(BeanUtilsStm.strRemoveBlank(x.getCashboxCode()));
        });
        SwStTvmCheckDetail swStTvmCheckDetail =   swStTvmCheckDetailDTO.getSwStTvmCheckDetail();
        List<Integer> wIds = swStTvmCheckDetailPapers.stream().map(SwStTvmCheckDetailPaper::getId).collect(Collectors.toList());
        List<SwStTvmCheckDetailPaper> wList = swStTvmCheckDetailPaperService.list(new QueryWrapper<SwStTvmCheckDetailPaper>().lambda().eq(SwStTvmCheckDetailPaper::getRelationId, rid));
        List<Integer> orginWIds = wList.stream().map(SwStTvmCheckDetailPaper::getId).collect(Collectors.toList());
        Collection<Integer> removeWIds = CollectionUtils.subtract(orginWIds, wIds);
        if (CollectionUtils.isNotEmpty(removeWIds)) {
            swStTvmCheckDetailPaperService.removeByIds(removeWIds);
        }
        List<SwStTvmCheckDetailPaper> haveTvm = swStTvmCheckDetailPaperService.list(new QueryWrapper<SwStTvmCheckDetailPaper>().lambda().eq(SwStTvmCheckDetailPaper::getRelationId, rid).eq(SwStTvmCheckDetailPaper::getTvmCode, swStTvmCheckDetail.getTvmCode()));
        if(CollectionUtil.isNotEmpty(haveTvm)){
            swStTvmCheckDetailPaperService.updateBatchById(swStTvmCheckDetailPapers);
        }else{
            swStTvmCheckDetailPaperService.saveBatch(swStTvmCheckDetailPapers);
        }
        //swStTvmCheckDetailPaperService.saveOrUpdateBatch(swStTvmCheckDetailPapers);
    }

    /**
     * 更新硬币回收箱  注意更新的时候支持 新增数据和删除数据
     * @param rid
     * @param swStTvmCheckDetailCoins
     */
    private void updateCoinData(SwStTvmCheckDetailDTO swStTvmCheckDetailDTO, Integer rid, List<SwStTvmCheckDetailCoin> swStTvmCheckDetailCoins) {
        swStTvmCheckDetailCoins.forEach(x -> {
            x.setRelationId(rid);
            //x.setCashboxCode(BeanUtilsStm.strRemoveBlank(x.getCashboxCode()));
        });
        SwStTvmCheckDetail swStTvmCheckDetail =   swStTvmCheckDetailDTO.getSwStTvmCheckDetail();
        List<Integer> wIds = swStTvmCheckDetailCoins.stream().map(SwStTvmCheckDetailCoin::getId).collect(Collectors.toList());
        List<SwStTvmCheckDetailCoin> wList = swStTvmCheckDetailCoinService.list(new QueryWrapper<SwStTvmCheckDetailCoin>().lambda().eq(SwStTvmCheckDetailCoin::getRelationId, rid));
        List<Integer> orginWIds = wList.stream().map(SwStTvmCheckDetailCoin::getId).collect(Collectors.toList());
        Collection<Integer> removeWIds = CollectionUtils.subtract(orginWIds, wIds);
        if (CollectionUtils.isNotEmpty(removeWIds)) {
            swStTvmCheckDetailCoinService.removeByIds(removeWIds);
        }
        List<SwStTvmCheckDetailCoin> haveTvm = swStTvmCheckDetailCoinService.list(new QueryWrapper<SwStTvmCheckDetailCoin>().lambda().eq(SwStTvmCheckDetailCoin::getRelationId, rid).eq(SwStTvmCheckDetailCoin::getTvmCode,swStTvmCheckDetail.getTvmCode()));
        if(CollectionUtil.isNotEmpty(haveTvm)){
            swStTvmCheckDetailCoinService.updateBatchById(swStTvmCheckDetailCoins);
        }else{
            swStTvmCheckDetailCoinService.saveBatch(swStTvmCheckDetailCoins);
        }
        //swStTvmCheckDetailCoinService.saveOrUpdateBatch(swStTvmCheckDetailCoins);
    }

    /**
     * 更新硬币找零箱  注意更新的时候支持 新增数据和删除数据
     * @param rid
     * @param swStTvmCheckDetailCoinChanges
     */
    private void updateCoinChangeData(SwStTvmCheckDetailDTO swStTvmCheckDetailDTO, Integer rid, List<SwStTvmCheckDetailCoinChange> swStTvmCheckDetailCoinChanges) {
        swStTvmCheckDetailCoinChanges.forEach(x -> {
            x.setRelationId(rid);
            //x.setCashboxCode(BeanUtilsStm.strRemoveBlank(x.getCashboxCode()));
        });
        SwStTvmCheckDetail swStTvmCheckDetail =   swStTvmCheckDetailDTO.getSwStTvmCheckDetail();
        List<Integer> wIds = swStTvmCheckDetailCoinChanges.stream().map(SwStTvmCheckDetailCoinChange::getId).collect(Collectors.toList());
        List<SwStTvmCheckDetailCoinChange> wList = swStTvmCheckDetailCoinChangeService.list(new QueryWrapper<SwStTvmCheckDetailCoinChange>().lambda().eq(SwStTvmCheckDetailCoinChange::getRelationId, rid));
        List<Integer> orginWIds = wList.stream().map(SwStTvmCheckDetailCoinChange::getId).collect(Collectors.toList());
        Collection<Integer> removeWIds = CollectionUtils.subtract(orginWIds, wIds);
        if (CollectionUtils.isNotEmpty(removeWIds)) {
            swStTvmCheckDetailCoinChangeService.removeByIds(removeWIds);
        }
        List<SwStTvmCheckDetailCoinChange> haveTvm = swStTvmCheckDetailCoinChangeService.list(new QueryWrapper<SwStTvmCheckDetailCoinChange>().lambda().eq(SwStTvmCheckDetailCoinChange::getRelationId, rid).eq(SwStTvmCheckDetailCoinChange::getTvmCode,swStTvmCheckDetail.getTvmCode()));
        if(CollectionUtil.isNotEmpty(haveTvm)){
            swStTvmCheckDetailCoinChangeService.updateBatchById(swStTvmCheckDetailCoinChanges);
        }else{
            swStTvmCheckDetailCoinChangeService.saveBatch(swStTvmCheckDetailCoinChanges);
        }
        //swStTvmCheckDetailCoinChangeService.saveOrUpdateBatch(swStTvmCheckDetailCoinChanges);
    }

    /**
     * 为了数据安全起见 删除暂时选用软删除的方式
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public boolean deleteCascadeById(Integer id) {
        //删除主表
        removeById(id);

        //删除从表
        swStTvmCheckDetailCoinChangeService.remove(new QueryWrapper<SwStTvmCheckDetailCoinChange>().lambda().eq(SwStTvmCheckDetailCoinChange::getRelationId, id));
        swStTvmCheckDetailCoinService.remove(new QueryWrapper<SwStTvmCheckDetailCoin>().lambda().eq(SwStTvmCheckDetailCoin::getRelationId, id));
        swStTvmCheckDetailPaperService.remove(new QueryWrapper<SwStTvmCheckDetailPaper>().lambda().eq(SwStTvmCheckDetailPaper::getRelationId, id));
        swStTvmCheckDetailPaperChangeService.remove(new QueryWrapper<SwStTvmCheckDetailPaperChange>().lambda().eq(SwStTvmCheckDetailPaperChange::getRelationId, id));
        stTvmCheckDetailWasteService.remove(new QueryWrapper<SwStTvmCheckDetailWaste>().lambda().eq(SwStTvmCheckDetailWaste::getRelationId, id));
        return true;
    }

    /**
     * 查询具体的详情
     *
     * @param id
     * @return
     */
    @Override
    public SwStTvmCheckDetailDTO queryDetailsByid(Integer id,String flag) {
        SwStTvmCheckDetailDTO swStTvmCheckDetailDTO = new SwStTvmCheckDetailDTO();
        //查询主表
        SwStTvmCheckDetail swStTvmCheckDetail = getById(id);
		//获取硬币找零箱和纸币找零箱的补币钱箱编号
		String lineCode = swStTvmCheckDetail.getLineCode();
		String stationCode = swStTvmCheckDetail.getStationCode();
		String tvmCode = swStTvmCheckDetail.getTvmCode();
		String revenueTime = DateUtilStm.localDateToString(swStTvmCheckDetail.getRevenueTime(),"yyyy-MM-dd");
		//String lineCode,String stationCode,String tvmCashBoxType,String revenueTime,String tvmCode,flag 待定怎么传
		//String flag = "1";//-------------------------------------todo---------------要和前台匹配
		/*List<Map<String, Object>> getSupplmentInfoCoin = StationSettleUtil.getSupplmentInfo(lineCode,stationCode,"2",revenueTime,tvmCode,flag);
		List<Map<String, Object>> getSupplmentInfoNote = StationSettleUtil.getSupplmentInfo(lineCode,stationCode,"4",revenueTime,tvmCode,flag); 
		if(getSupplmentInfoCoin!=null && getSupplmentInfoCoin.size()>0){		 
				Map<String,Object>  map  = getSupplmentInfoCoin.get(0);
			    swStTvmCheckDetail.setCoinChangeCashBoxCode(String.valueOf(map.get("cashboxcode")));
		}

        if(getSupplmentInfoNote!=null && getSupplmentInfoNote.size()>0){		 
				Map<String,Object>  map  = getSupplmentInfoNote.get(0);
			    swStTvmCheckDetail.setNoteChangeCashBoxCode(String.valueOf(map.get("cashboxcode")));
		}*/


        List<SwStTvmCheckDetailCoinChange> swStTvmCheckDetailCoinChanges = swStTvmCheckDetailCoinChangeService.list(new QueryWrapper<SwStTvmCheckDetailCoinChange>().lambda().eq(SwStTvmCheckDetailCoinChange::getRelationId, id));
        List<SwStTvmCheckDetailCoin> swStTvmCheckDetailCoins = swStTvmCheckDetailCoinService.list(new QueryWrapper<SwStTvmCheckDetailCoin>().lambda().eq(SwStTvmCheckDetailCoin::getRelationId, id));
        List<SwStTvmCheckDetailPaper> swStTvmCheckDetailPapers = swStTvmCheckDetailPaperService.list(new QueryWrapper<SwStTvmCheckDetailPaper>().lambda().eq(SwStTvmCheckDetailPaper::getRelationId, id));
        List<SwStTvmCheckDetailPaperChange> swStTvmCheckDetailPaperChanges = swStTvmCheckDetailPaperChangeService.list(new QueryWrapper<SwStTvmCheckDetailPaperChange>().lambda().eq(SwStTvmCheckDetailPaperChange::getRelationId, id));
        List<SwStTvmCheckDetailWaste> swStTvmCheckDetailWastes = stTvmCheckDetailWasteService.list(new QueryWrapper<SwStTvmCheckDetailWaste>().lambda().eq(SwStTvmCheckDetailWaste::getRelationId, id));
        swStTvmCheckDetailDTO.setSwStTvmCheckDetailCoinChanges(swStTvmCheckDetailCoinChanges);
        swStTvmCheckDetailDTO.setSwStTvmCheckDetailCoins(swStTvmCheckDetailCoins);
        swStTvmCheckDetailDTO.setSwStTvmCheckDetailPaperChanges(swStTvmCheckDetailPaperChanges);
        swStTvmCheckDetailDTO.setSwStTvmCheckDetailPapers(swStTvmCheckDetailPapers);
        swStTvmCheckDetailDTO.setSwStTvmCheckDetailWastes(swStTvmCheckDetailWastes);
        swStTvmCheckDetailDTO.setSwStTvmCheckDetail(swStTvmCheckDetail);
        return swStTvmCheckDetailDTO;
    }

    @Override
    public boolean updateSwStTvmCheckDetailApprovalStatus(List<Integer> ids, String status) {
        if (CollectionUtils.isEmpty(ids)) {
            return false;
        }
        List<SwStTvmCheckDetail> updateData = new ArrayList<>();
        for (Integer id : ids) {
            SwStTvmCheckDetail sw = new SwStTvmCheckDetail();
            sw.setId(id);
            sw.setApprovalStatus(status);
            updateData.add(sw);
        }
        return updateBatchById(updateData);
    }

    /**
     * 新增数据或者更新数据
     *
     * @param swStTvmCheckDetailDTO
     * @return
     * @date 2020-8-2新增
     */
    @Override
    @Transactional
    public boolean saveOrUpdateStTvmCheckDetail(SwStTvmCheckDetailDTO swStTvmCheckDetailDTO,Integer id) throws SQLException {
        log.info("beforeSave data time {} dto:{}", LocalDateTime.now(), JSON.toJSONString(swStTvmCheckDetailDTO));
        //1:当前单表保存的数据 可能是添加也可能是更新 硬币回收箱
        SwStTvmCheckDetail swStTvmCheckDetail = swStTvmCheckDetailDTO.getSwStTvmCheckDetail();
        if (swStTvmCheckDetail.getCheckTime() == null) {
            swStTvmCheckDetail.setCheckTime(DateUtilStm.localDateToString(LocalDate.now()));
            swStTvmCheckDetail.setRevenueTime(LocalDate.now());
        }
        LocalDate revenueTime = swStTvmCheckDetail.getRevenueTime();
        SwStTvmCheckDetail swStTvmCheckDetailObj = ObjectUtils.getDefaultObj(SwStTvmCheckDetail.class);
        BeanUtil.copyProperties(swStTvmCheckDetailObj, swStTvmCheckDetail, CopyOptions.create().setIgnoreNullValue(true));
        //钱箱未卸载
        List<SwStInputCashboxUninstalled> swStInputCashboxUninstalleds = new ArrayList<>();
        PigxUser user = SecurityUtils.getUser();
        boolean flag = true;
        //todo 增加提醒功能：当录入同一结算周期范围内相同TVM编号两条数据时增加提醒功能，禁止录入
        List<Map<String,Object>> tvmListMap = getTvmListMap(swStTvmCheckDetail, revenueTime);
        if(CollectionUtil.isEmpty(tvmListMap) || tvmListMap == null){
            throw new RuntimeException("周期范围之外的数据不允许录入！");
        }
        List<SwStTvmCheckDetailCoin> swStTvmCheckDetailCoins = swStTvmCheckDetailDTO.getSwStTvmCheckDetailCoins();
        //1:保存支持多个的能力  当前一个一个传也是支持的
        if (CollectionUtils.isNotEmpty(swStTvmCheckDetailCoins)) {
            //1.1统计  按照tvm进行分组
            Map<String, List<SwStTvmCheckDetailCoin>> countMap = swStTvmCheckDetailCoins.stream().collect(Collectors.groupingBy(swKey -> swKey.getTvmCode()));
            log.info("beforeSave data time {} countMap:{}", LocalDateTime.now(), JSON.toJSONString(countMap));
            Set<String> tvmSet = countMap.keySet();
            for (String tvmCode : tvmSet) {
                //根据tvm查询主表 如果查到了直接更新 查不到的话直接点击添加即可
                SwStTvmCheckDetail mainTable = getMainTable(swStTvmCheckDetail, revenueTime, tvmCode);
                if (null != mainTable) {
                    //1:复用以前接口 查询主表详情 并更新主表详情
                    SwStTvmCheckDetailDTO tvmDto = queryDetailsByid(mainTable.getId(),"1");
                    //有这么一种场景 假如A是1月1日新增的 1月2日在来新增 但是日期填错了填成1.1 所以查询出来的数据是1月1日的 所以这里不让他进行修改数据默认是失败的
                    if (tvmDto.getSwStTvmCheckDetailCoins().size()>0 && id==1) {
                        throw new RuntimeException("请检查TVM编号为" + tvmCode + "的在" + swStTvmCheckDetail.getRevenueTime() + "数据已存在！");
                    }
                    tvmDto.setSwStTvmCheckDetailCoins(countMap.get(tvmCode));
                    log.info("beforeUpdate data time {} tvmDto:{}", LocalDateTime.now(), JSON.toJSONString(tvmDto));
                    updateSwStTvmCheckDetail(tvmDto);
                } else {
                    //todo 增加提醒功能：当录入同一结算周期范围内相同TVM编号两条数据时增加提醒功能，禁止录入
                    List<SwStTvmCheckDetail> tvmList = getTvmList(swStTvmCheckDetail,tvmListMap,tvmCode);
                    if(CollectionUtil.isNotEmpty(tvmList)){
                        throw new RuntimeException("该周期内已存在TVM编号为" + tvmCode + "的数据！");
                    }
                    SwStTvmCheckDetailDTO saveTto = new SwStTvmCheckDetailDTO();
                    saveTto.setSwStTvmCheckDetailCoins(countMap.get(tvmCode));
                    saveTto.setSwStTvmCheckDetail(swStTvmCheckDetail);
                    log.info("beforeSave data time {} saveTto:{}", LocalDateTime.now(), JSON.toJSONString(saveTto));
                    saveSwStTvmCheckDetail(saveTto);
                }
            }
            //钱箱未卸载
            flag = false;
            for (SwStTvmCheckDetailCoin coin : swStTvmCheckDetailCoins) {
                if (null != coin.getId() && !"3".equals(coin.getUnloadCase())) {//未卸载
                    SwStInputCashboxUninstalled cashBox = new SwStInputCashboxUninstalled();
                    cashBox.setTvmCode(coin.getTvmCode());
                    cashBox.setLineCode(user.getLineCode());
                    cashBox.setStationCode(user.getStationCode());
                    cashBox.setMoneyBoxType("硬币回收箱");
                    //cashBox.setMoneyBoxCode(coin.getCashboxCode());
                    cashBox.setShouldBeUnloadedAmount(coin.getSysAmount());
                    cashBox.setUninstallAmount(coin.getRealAmount());
                    cashBox.setDifferenceAmount(coin.getDiffAmount());
                    cashBox.setCheckPersonName(swStTvmCheckDetail.getCheckPersonTwoName());
                    cashBox.setInventoryPersonJobNo(swStTvmCheckDetail.getCheckPersonTwoJopNo());
                    cashBox.setInventoryPersonId(swStTvmCheckDetail.getCheckPersonTwoId());
                    cashBox.setIsSubmit("0");
                    cashBox.setUninstalledDate(swStTvmCheckDetail.getRevenueTime());
                    swStInputCashboxUninstalleds.add(cashBox);
                }
				//20241118 线路，车站，TVM编号，钱箱类型
            }
        }
        List<SwStTvmCheckDetailCoinChange> swStTvmCheckDetailCoinChanges = swStTvmCheckDetailDTO.getSwStTvmCheckDetailCoinChanges();
        //3:保存支持多个的能力  当前一个一个传也是支持的
        if (CollectionUtils.isNotEmpty(swStTvmCheckDetailCoinChanges)) {
            //1.1统计  按照tvm进行分组
            Map<String, List<SwStTvmCheckDetailCoinChange>> countMap = swStTvmCheckDetailCoinChanges.stream().collect(Collectors.groupingBy(swKey -> swKey.getTvmCode()));
            log.info("beforeSave data time {} countMap:{}", LocalDateTime.now(), JSON.toJSONString(countMap));
            Set<String> tvmSet = countMap.keySet();
            for (String tvmCode : tvmSet) {
                //根据tvm查询主表 如果查到了直接更新 查不到的话直接点击添加即可
                SwStTvmCheckDetail mainTable = getMainTable(swStTvmCheckDetail, revenueTime, tvmCode);
                if (null != mainTable) {
                    //1:复用以前接口 查询主表详情 并更新主表详情  修改时候应该是单条修改的
                    SwStTvmCheckDetailDTO tvmDto = queryDetailsByid(mainTable.getId(),"1");
                    if (tvmDto.getSwStTvmCheckDetailCoinChanges().size()>0 && id==1) {
                        throw new RuntimeException("请检查TVM编号为" + tvmCode + "的在" + swStTvmCheckDetail.getRevenueTime() + "数据已存在！");
                    }
                    /*if (tvmDto.getSwStTvmCheckDetailCoinChanges() != null) {
                        throw new RuntimeException("tvm-" + tvmCode + "in date" + swStTvmCheckDetail.getRevenueTime() + "has already add");
                    }*/
                    tvmDto.setSwStTvmCheckDetailCoinChanges(countMap.get(tvmCode));
                    log.info("beforeUpdate data time {} tvmDto:{}", LocalDateTime.now(), JSON.toJSONString(tvmDto));
                    updateSwStTvmCheckDetail(tvmDto);
                } else {
                    //todo 增加提醒功能：当录入同一结算周期范围内相同TVM编号两条数据时增加提醒功能，禁止录入
                    List<SwStTvmCheckDetail> tvmList = getTvmList(swStTvmCheckDetail,tvmListMap,tvmCode);
                    if(CollectionUtil.isNotEmpty(tvmList)){
                        throw new RuntimeException("该周期内已存在TVM编号为" + tvmCode + "的数据！");
                    }
                    SwStTvmCheckDetailDTO saveTto = new SwStTvmCheckDetailDTO();
                    saveTto.setSwStTvmCheckDetailCoinChanges(countMap.get(tvmCode));
                    saveTto.setSwStTvmCheckDetail(swStTvmCheckDetail);
                    log.info("beforeSave data time {} saveTto:{}", LocalDateTime.now(), JSON.toJSONString(saveTto));
                    saveSwStTvmCheckDetail(saveTto);
                }
            }
            flag = false;
            for (SwStTvmCheckDetailCoinChange change : swStTvmCheckDetailCoinChanges) {
                if (null != change.getId() && !"3".equals(change.getUnloadCase())) {
                    SwStInputCashboxUninstalled cashBox = new SwStInputCashboxUninstalled();
                    cashBox.setTvmCode(change.getTvmCode());
                    cashBox.setLineCode(user.getLineCode());
                    cashBox.setStationCode(user.getStationCode());
                    cashBox.setMoneyBoxType("硬币找零箱");
                    //cashBox.setMoneyBoxCode(change.getCashboxCode());
                    cashBox.setShouldBeUnloadedAmount(change.getSysAmount());
                    cashBox.setUninstallAmount(change.getRealAmount());
                    cashBox.setDifferenceAmount(change.getDiffAmount());
                    cashBox.setCheckPersonName(swStTvmCheckDetail.getCheckPersonTwoName());
                    cashBox.setInventoryPersonJobNo(swStTvmCheckDetail.getCheckPersonTwoJopNo());
                    cashBox.setInventoryPersonId(swStTvmCheckDetail.getCheckPersonTwoId());
                    cashBox.setIsSubmit("0");
                    cashBox.setUninstalledDate(swStTvmCheckDetail.getRevenueTime());
                    swStInputCashboxUninstalleds.add(cashBox);
                }
            }
        }
        List<SwStTvmCheckDetailPaper> swStTvmCheckDetailPapers = swStTvmCheckDetailDTO.getSwStTvmCheckDetailPapers();
        //4:保存支持多个的能力  当前一个一个传也是支持的
        if (CollectionUtils.isNotEmpty(swStTvmCheckDetailPapers)) {
            //1.1统计  按照tvm进行分组
            Map<String, List<SwStTvmCheckDetailPaper>> countMap = swStTvmCheckDetailPapers.stream().collect(Collectors.groupingBy(swKey -> swKey.getTvmCode()));
            log.info("beforeSave data time {} countMap:{}", LocalDateTime.now(), JSON.toJSONString(countMap));
            Set<String> tvmSet = countMap.keySet();
            for (String tvmCode : tvmSet) {
                //根据tvm查询主表 如果查到了直接更新 查不到的话直接点击添加即可
                SwStTvmCheckDetail mainTable = getMainTable(swStTvmCheckDetail, revenueTime, tvmCode);
                if (null != mainTable) {
                    //1:复用以前接口 查询主表详情 并更新主表详情
                    SwStTvmCheckDetailDTO tvmDto = queryDetailsByid(mainTable.getId(),"1");
                    if (tvmDto.getSwStTvmCheckDetailPapers().size()>0 && id==1) {
                        throw new RuntimeException("请检查TVM编号为" + tvmCode + "的在" + swStTvmCheckDetail.getRevenueTime() + "数据已存在！");
                    }
                    /*if (tvmDto.getSwStTvmCheckDetailPapers() != null) {
                        throw new RuntimeException("tvm-" + tvmCode + "in date" + swStTvmCheckDetail.getRevenueTime() + "has already add");
                    }*/
                    tvmDto.setSwStTvmCheckDetailPapers(countMap.get(tvmCode));
                    log.info("beforeUpdate data time {} tvmDto:{}", LocalDateTime.now(), JSON.toJSONString(tvmDto));
                    updateSwStTvmCheckDetail(tvmDto);
                } else {
                    //todo 增加提醒功能：当录入同一结算周期范围内相同TVM编号两条数据时增加提醒功能，禁止录入
                    List<SwStTvmCheckDetail> tvmList = getTvmList(swStTvmCheckDetail,tvmListMap,tvmCode);
                    if(CollectionUtil.isNotEmpty(tvmList)){
                        throw new RuntimeException("该周期内已存在TVM编号为" + tvmCode + "的数据！");
                    }
                    SwStTvmCheckDetailDTO saveTto = new SwStTvmCheckDetailDTO();
                    saveTto.setSwStTvmCheckDetailPapers(countMap.get(tvmCode));
                    saveTto.setSwStTvmCheckDetail(swStTvmCheckDetail);
                    log.info("beforeSave data time {} saveTto:{}", LocalDateTime.now(), JSON.toJSONString(saveTto));
                    saveSwStTvmCheckDetail(saveTto);
                }
            }
            flag = false;
            for (SwStTvmCheckDetailPaper paper : swStTvmCheckDetailPapers) {
                if (null != paper.getId() && !"3".equals(paper.getUnloadCase())) {
                    SwStInputCashboxUninstalled cashBox = new SwStInputCashboxUninstalled();
                    cashBox.setTvmCode(paper.getTvmCode());
                    cashBox.setLineCode(user.getLineCode());
                    cashBox.setStationCode(user.getStationCode());
                    cashBox.setMoneyBoxType("纸币回收箱");
                    //cashBox.setMoneyBoxCode(paper.getCashboxCode());
                    cashBox.setShouldBeUnloadedAmount(paper.getSysAmount());
                    cashBox.setUninstallAmount(paper.getRealAmount());
                    cashBox.setDifferenceAmount(paper.getDiffAmount());
                    cashBox.setCheckPersonName(swStTvmCheckDetail.getCheckPersonTwoName());
                    cashBox.setInventoryPersonJobNo(swStTvmCheckDetail.getCheckPersonTwoJopNo());
                    cashBox.setInventoryPersonId(swStTvmCheckDetail.getCheckPersonTwoId());
                    cashBox.setIsSubmit("0");
                    cashBox.setUninstalledDate(swStTvmCheckDetail.getRevenueTime());
                    swStInputCashboxUninstalleds.add(cashBox);
                }
            }
        }
        List<SwStTvmCheckDetailPaperChange> swStTvmCheckDetailPaperChanges = swStTvmCheckDetailDTO.getSwStTvmCheckDetailPaperChanges();
        //5:保存支持多个的能力  当前一个一个传也是支持的
        if (CollectionUtils.isNotEmpty(swStTvmCheckDetailPaperChanges)) {
            //1.1统计  按照tvm进行分组
            Map<String, List<SwStTvmCheckDetailPaperChange>> countMap = swStTvmCheckDetailPaperChanges.stream().collect(Collectors.groupingBy(swKey -> swKey.getTvmCode()));
            log.info("beforeSave data time {} countMap:{}", LocalDateTime.now(), JSON.toJSONString(countMap));
            Set<String> tvmSet = countMap.keySet();
            for (String tvmCode : tvmSet) {
                //根据tvm查询主表 如果查到了直接更新 查不到的话直接点击添加即可
                SwStTvmCheckDetail mainTable = getMainTable(swStTvmCheckDetail, revenueTime, tvmCode);
                if (null != mainTable) {
                    //1:复用以前接口 查询主表详情 并更新主表详情
                    SwStTvmCheckDetailDTO tvmDto = queryDetailsByid(mainTable.getId(),"1");
                    if (tvmDto.getSwStTvmCheckDetailPaperChanges().size()>0 && id==1) {
                        throw new RuntimeException("请检查TVM编号为" + tvmCode + "的在" + swStTvmCheckDetail.getRevenueTime() + "数据已存在！");
                    }
                    /*if (tvmDto.getSwStTvmCheckDetailPaperChanges() != null) {
                        throw new RuntimeException("tvm-" + tvmCode + "in date" + swStTvmCheckDetail.getRevenueTime() + "has already add");
                    }*/
                    tvmDto.setSwStTvmCheckDetailPaperChanges(countMap.get(tvmCode));
                    log.info("beforeUpdate data time {} tvmDto:{}", LocalDateTime.now(), JSON.toJSONString(tvmDto));
                    updateSwStTvmCheckDetail(tvmDto);
                } else {
                    //todo 增加提醒功能：当录入同一结算周期范围内相同TVM编号两条数据时增加提醒功能，禁止录入
                    List<SwStTvmCheckDetail> tvmList = getTvmList(swStTvmCheckDetail,tvmListMap,tvmCode);
                    if(CollectionUtil.isNotEmpty(tvmList)){
                        throw new RuntimeException("该周期内已存在TVM编号为" + tvmCode + "的数据！");
                    }
                    SwStTvmCheckDetailDTO saveTto = new SwStTvmCheckDetailDTO();
                    saveTto.setSwStTvmCheckDetailPaperChanges(countMap.get(tvmCode));
                    saveTto.setSwStTvmCheckDetail(swStTvmCheckDetail);
                    log.info("beforeSave data time {} saveTto:{}", LocalDateTime.now(), JSON.toJSONString(saveTto));
                    saveSwStTvmCheckDetail(saveTto);
                }
            }flag = false;
            for (SwStTvmCheckDetailPaperChange paperChange : swStTvmCheckDetailPaperChanges) {
                if (null != paperChange.getId() && !"3".equals(paperChange.getUnloadCase())) {
                    SwStInputCashboxUninstalled cashBox = new SwStInputCashboxUninstalled();
                    cashBox.setTvmCode(paperChange.getTvmCode());
                    cashBox.setLineCode(user.getLineCode());
                    cashBox.setStationCode(user.getStationCode());
                    cashBox.setMoneyBoxType("纸币找零箱");
                    //cashBox.setMoneyBoxCode(paperChange.getCashboxCode());
                    cashBox.setShouldBeUnloadedAmount(paperChange.getSysAmount());
                    cashBox.setUninstallAmount(paperChange.getRealAmount());
                    cashBox.setDifferenceAmount(paperChange.getDiffAmount());
                    cashBox.setCheckPersonName(swStTvmCheckDetail.getCheckPersonTwoName());
                    cashBox.setInventoryPersonJobNo(swStTvmCheckDetail.getCheckPersonTwoJopNo());
                    cashBox.setInventoryPersonId(swStTvmCheckDetail.getCheckPersonTwoId());
                    cashBox.setIsSubmit("0");
                    cashBox.setUninstalledDate(swStTvmCheckDetail.getRevenueTime());
                    swStInputCashboxUninstalleds.add(cashBox);
                }
            }
        }
        List<SwStTvmCheckDetailWaste> swStTvmCheckDetailWastes = swStTvmCheckDetailDTO.getSwStTvmCheckDetailWastes();
        //2:保存支持多个的能力  当前一个一个传也是支持的
        if (CollectionUtils.isNotEmpty(swStTvmCheckDetailWastes)) {
            //1.1统计  按照tvm进行分组
            Map<String, List<SwStTvmCheckDetailWaste>> countMap = swStTvmCheckDetailWastes.stream().collect(Collectors.groupingBy(swKey -> swKey.getTvmCode()));
            log.info("beforeSave data time {} countMap:{}", LocalDateTime.now(), JSON.toJSONString(countMap));
            Set<String> tvmSet = countMap.keySet();
            for (String tvmCode : tvmSet) {
                //根据tvm查询主表 如果查到了直接更新 查不到的话直接点击添加即可
                SwStTvmCheckDetail mainTable = getMainTable(swStTvmCheckDetail, revenueTime, tvmCode);
                if (null != mainTable) {
                    //1:复用以前接口 查询主表详情 并更新主表详情
                    SwStTvmCheckDetailDTO tvmDto = queryDetailsByid(mainTable.getId(),"1");
                    if (tvmDto.getSwStTvmCheckDetailWastes().size()>0 && id==1) {
                        throw new RuntimeException("请检查TVM编号为" + tvmCode + "的在" + swStTvmCheckDetail.getRevenueTime() + "数据已存在！");
                    }
                    /*if (tvmDto.getSwStTvmCheckDetailWastes() != null) {
                        throw new RuntimeException("tvm-" + tvmCode + "in date" + swStTvmCheckDetail.getRevenueTime() + "has already add");
                    }*/
                    tvmDto.setSwStTvmCheckDetailWastes(countMap.get(tvmCode));
                    log.info("beforeUpdate data time {} tvmDto:{}", LocalDateTime.now(), JSON.toJSONString(tvmDto));
                    updateSwStTvmCheckDetail(tvmDto);
                } else {
                    //todo 增加提醒功能：当录入同一结算周期范围内相同TVM编号两条数据时增加提醒功能，禁止录入
                    List<SwStTvmCheckDetail> tvmList = getTvmList(swStTvmCheckDetail,tvmListMap,tvmCode);
                    if(CollectionUtil.isNotEmpty(tvmList)){
                        throw new RuntimeException("该周期内已存在TVM编号为" + tvmCode + "的数据！");
                    }
                    SwStTvmCheckDetailDTO saveTto = new SwStTvmCheckDetailDTO();
                    saveTto.setSwStTvmCheckDetailWastes(countMap.get(tvmCode));
                    saveTto.setSwStTvmCheckDetail(swStTvmCheckDetail);
                    log.info("beforeSave data time {} saveTto:{}", LocalDateTime.now(), JSON.toJSONString(saveTto));
                    saveSwStTvmCheckDetail(saveTto);
                }
            }
            flag = false;
            for (SwStTvmCheckDetailWaste wastes : swStTvmCheckDetailWastes) {
                if (null != wastes.getId() && !"3".equals(wastes.getUnloadCase())) {
                    SwStInputCashboxUninstalled cashBox = new SwStInputCashboxUninstalled();
                    cashBox.setTvmCode(wastes.getTvmCode());
                    cashBox.setLineCode(user.getLineCode());
                    cashBox.setStationCode(user.getStationCode());
                    cashBox.setMoneyBoxType("废钞箱");
                    //cashBox.setMoneyBoxCode(wastes.getCashboxCode());
                    cashBox.setShouldBeUnloadedAmount(wastes.getSysAmount());
                    cashBox.setUninstallAmount(wastes.getRealAmount());
                    cashBox.setDifferenceAmount(wastes.getDiffAmount());
                    cashBox.setCheckPersonName(swStTvmCheckDetail.getCheckPersonTwoName());
                    cashBox.setInventoryPersonJobNo(swStTvmCheckDetail.getCheckPersonTwoJopNo());
                    cashBox.setInventoryPersonId(swStTvmCheckDetail.getCheckPersonTwoId());
                    cashBox.setIsSubmit("0");
                    cashBox.setUninstalledDate(swStTvmCheckDetail.getRevenueTime());
                    swStInputCashboxUninstalleds.add(cashBox);
                }
            }
        }
        //未卸载的添加到钱箱未卸载钱箱
        if (CollectionUtil.isNotEmpty(swStInputCashboxUninstalleds)) {
            swStInputCashboxUninstalledService.saveBatch(swStInputCashboxUninstalleds);
        }
        return true;
    }

    /**
     * 此方法未用到
     * @param swStTvmCheckDetailDTO
     * @return
     * @throws SQLException
     */
    @Override
    public Integer updateSwStOneCashBox(SwStTvmCheckDetailDTO swStTvmCheckDetailDTO) {
        SwStTvmCheckDetail swStTvmCheckDetail = swStTvmCheckDetailDTO.getSwStTvmCheckDetail();
        List<SwStTvmCheckDetailCoin> swStTvmCheckDetailCoins = swStTvmCheckDetailDTO.getSwStTvmCheckDetailCoins();
        List<SwStInputCashboxUninstalled> swStInputCashboxUninstalleds = new ArrayList<>();
        PigxUser user = SecurityUtils.getUser();
        String tvmCode = "";

        boolean flag = true;

        if (null == swStTvmCheckDetail.getId()) {
            swStTvmCheckDetail.setLineCode(user.getLineCode());
            swStTvmCheckDetail.setStationCode(user.getStationCode());
            save(swStTvmCheckDetail);
        }
        /**
         * 更新硬币箱
         */
        if (CollectionUtils.isNotEmpty(swStTvmCheckDetailCoins)) {
            flag = false;
            for (SwStTvmCheckDetailCoin coin : swStTvmCheckDetailCoins) {
                if (null == coin.getId() && !coin.getUnloadCase().equals("3")) {
                    SwStInputCashboxUninstalled cashBox = new SwStInputCashboxUninstalled();
                    cashBox.setTvmCode(coin.getTvmCode());
                    cashBox.setLineCode(user.getLineCode());
                    cashBox.setStationCode(user.getStationCode());
                    cashBox.setMoneyBoxType("硬币回收箱");
                    //cashBox.setMoneyBoxCode(coin.getCashboxCode());
                    cashBox.setUninstallDate(LocalDate.now());
                    cashBox.setShouldBeUnloadedAmount(coin.getSysAmount());
                    cashBox.setUninstallAmount(coin.getRealAmount());
                    cashBox.setDifferenceAmount(coin.getDiffAmount());
                    cashBox.setCheckPersonName(swStTvmCheckDetail.getCheckPersonTwoName());
                    cashBox.setInventoryPersonJobNo(swStTvmCheckDetail.getCheckPersonTwoJopNo());
                    cashBox.setInventoryPersonId(swStTvmCheckDetail.getCheckPersonTwoId());
                    cashBox.setIsSubmit("0");
                    cashBox.setUninstalledDate(swStTvmCheckDetail.getRevenueTime());
                    swStInputCashboxUninstalleds.add(cashBox);
                }
            }
            SwStTvmCheckDetailDTO tvmDto = queryDetailsByid(swStTvmCheckDetail.getId(),"1");
            tvmDto.setSwStTvmCheckDetailCoins(swStTvmCheckDetailCoins);
            tvmDto.setSwStTvmCheckDetail(swStTvmCheckDetail);
            updateSwStTvmCheckDetail(tvmDto);
            tvmCode = swStTvmCheckDetailCoins.get(0).getTvmCode();


        }

        List<SwStTvmCheckDetailCoinChange> swStTvmCheckDetailCoinChanges = swStTvmCheckDetailDTO.getSwStTvmCheckDetailCoinChanges();
        if (CollectionUtils.isNotEmpty(swStTvmCheckDetailCoinChanges)) {
            flag = false;
            for (SwStTvmCheckDetailCoinChange change : swStTvmCheckDetailCoinChanges) {
                if (null == change.getId() && !change.getUnloadCase().equals("3")) {
                    SwStInputCashboxUninstalled cashBox = new SwStInputCashboxUninstalled();
                    cashBox.setTvmCode(change.getTvmCode());
                    cashBox.setLineCode(user.getLineCode());
                    cashBox.setStationCode(user.getStationCode());
                    cashBox.setMoneyBoxType("硬币找零箱");
                    //cashBox.setMoneyBoxCode(change.getCashboxCode());
                    cashBox.setUninstallDate(LocalDate.now());
                    cashBox.setShouldBeUnloadedAmount(change.getSysAmount());
                    cashBox.setUninstallAmount(change.getRealAmount());
                    cashBox.setDifferenceAmount(change.getDiffAmount());
                    cashBox.setCheckPersonName(swStTvmCheckDetail.getCheckPersonTwoName());
                    cashBox.setInventoryPersonJobNo(swStTvmCheckDetail.getCheckPersonTwoJopNo());
                    cashBox.setInventoryPersonId(swStTvmCheckDetail.getCheckPersonTwoId());
                    cashBox.setIsSubmit("0");
                    cashBox.setUninstalledDate(swStTvmCheckDetail.getRevenueTime());
                    swStInputCashboxUninstalleds.add(cashBox);
                }
            }
            SwStTvmCheckDetailDTO tvmDto = queryDetailsByid(swStTvmCheckDetail.getId(),"1");
            tvmDto.setSwStTvmCheckDetail(swStTvmCheckDetail);
            tvmDto.setSwStTvmCheckDetailCoinChanges(swStTvmCheckDetailCoinChanges);
            updateSwStTvmCheckDetail(tvmDto);
            tvmCode = swStTvmCheckDetailCoinChanges.get(0).getTvmCode();


        }

        List<SwStTvmCheckDetailPaper> swStTvmCheckDetailPapers = swStTvmCheckDetailDTO.getSwStTvmCheckDetailPapers();
        if (CollectionUtils.isNotEmpty(swStTvmCheckDetailPapers)) {
            flag = false;
            for (SwStTvmCheckDetailPaper paper : swStTvmCheckDetailPapers) {
                if (null == paper.getId() && !paper.getUnloadCase().equals("3")) {
                    SwStInputCashboxUninstalled cashBox = new SwStInputCashboxUninstalled();
                    cashBox.setTvmCode(paper.getTvmCode());
                    cashBox.setLineCode(user.getLineCode());
                    cashBox.setStationCode(user.getStationCode());
                    cashBox.setMoneyBoxType("纸币回收箱");
                    //cashBox.setMoneyBoxCode(paper.getCashboxCode());
                    cashBox.setUninstallDate(LocalDate.now());
                    cashBox.setShouldBeUnloadedAmount(paper.getSysAmount());
                    cashBox.setUninstallAmount(paper.getRealAmount());
                    cashBox.setDifferenceAmount(paper.getDiffAmount());
                    cashBox.setCheckPersonName(swStTvmCheckDetail.getCheckPersonTwoName());
                    cashBox.setInventoryPersonJobNo(swStTvmCheckDetail.getCheckPersonTwoJopNo());
                    cashBox.setInventoryPersonId(swStTvmCheckDetail.getCheckPersonTwoId());
                    cashBox.setIsSubmit("0");
                    cashBox.setUninstalledDate(swStTvmCheckDetail.getRevenueTime());
                    swStInputCashboxUninstalleds.add(cashBox);
                }
            }
            SwStTvmCheckDetailDTO tvmDto = queryDetailsByid(swStTvmCheckDetail.getId(),"1");
            tvmDto.setSwStTvmCheckDetail(swStTvmCheckDetail);
            tvmDto.setSwStTvmCheckDetailPapers(swStTvmCheckDetailPapers);
            updateSwStTvmCheckDetail(tvmDto);
            tvmCode = swStTvmCheckDetailPapers.get(0).getTvmCode();

        }

        List<SwStTvmCheckDetailPaperChange> swStTvmCheckDetailPaperChanges = swStTvmCheckDetailDTO.getSwStTvmCheckDetailPaperChanges();
        if (CollectionUtils.isNotEmpty(swStTvmCheckDetailPaperChanges)) {
            flag = false;
            for (SwStTvmCheckDetailPaperChange paperChange : swStTvmCheckDetailPaperChanges) {
                if (null == paperChange.getId() && !paperChange.getUnloadCase().equals("3")) {
                    SwStInputCashboxUninstalled cashBox = new SwStInputCashboxUninstalled();
                    cashBox.setTvmCode(paperChange.getTvmCode());
                    cashBox.setLineCode(user.getLineCode());
                    cashBox.setStationCode(user.getStationCode());
                    cashBox.setMoneyBoxType("纸币找零箱");
                    //cashBox.setMoneyBoxCode(paperChange.getCashboxCode());
                    cashBox.setUninstallDate(LocalDate.now());
                    cashBox.setShouldBeUnloadedAmount(paperChange.getSysAmount());
                    cashBox.setUninstallAmount(paperChange.getRealAmount());
                    cashBox.setDifferenceAmount(paperChange.getDiffAmount());
                    cashBox.setCheckPersonName(swStTvmCheckDetail.getCheckPersonTwoName());
                    cashBox.setInventoryPersonJobNo(swStTvmCheckDetail.getCheckPersonTwoJopNo());
                    cashBox.setInventoryPersonId(swStTvmCheckDetail.getCheckPersonTwoId());
                    cashBox.setIsSubmit("0");
                    cashBox.setUninstalledDate(swStTvmCheckDetail.getRevenueTime());
                    swStInputCashboxUninstalleds.add(cashBox);
                }
            }
            SwStTvmCheckDetailDTO tvmDto = queryDetailsByid(swStTvmCheckDetail.getId(),"1");
            tvmDto.setSwStTvmCheckDetail(swStTvmCheckDetail);
            tvmDto.setSwStTvmCheckDetailPaperChanges(swStTvmCheckDetailPaperChanges);
            updateSwStTvmCheckDetail(tvmDto);
            tvmCode = swStTvmCheckDetailPaperChanges.get(0).getTvmCode();

        }
        List<SwStTvmCheckDetailWaste> swStTvmCheckDetailWastes = swStTvmCheckDetailDTO.getSwStTvmCheckDetailWastes();
        if (CollectionUtils.isNotEmpty(swStTvmCheckDetailWastes)) {
            flag = false;
            for (SwStTvmCheckDetailWaste wastes : swStTvmCheckDetailWastes) {
                if (null == wastes.getId() && !wastes.getUnloadCase().equals("3")) {
                    SwStInputCashboxUninstalled cashBox = new SwStInputCashboxUninstalled();
                    cashBox.setTvmCode(wastes.getTvmCode());
                    cashBox.setLineCode(user.getLineCode());
                    cashBox.setStationCode(user.getStationCode());
                    cashBox.setMoneyBoxType("废钞箱");
                    //cashBox.setMoneyBoxCode(wastes.getCashboxCode());
                    cashBox.setUninstallDate(LocalDate.now());
                    cashBox.setShouldBeUnloadedAmount(wastes.getSysAmount());
                    cashBox.setUninstallAmount(wastes.getRealAmount());
                    cashBox.setDifferenceAmount(wastes.getDiffAmount());
                    cashBox.setCheckPersonName(swStTvmCheckDetail.getCheckPersonTwoName());
                    cashBox.setInventoryPersonJobNo(swStTvmCheckDetail.getCheckPersonTwoJopNo());
                    cashBox.setInventoryPersonId(swStTvmCheckDetail.getCheckPersonTwoId());
                    cashBox.setIsSubmit("0");
                    cashBox.setUninstalledDate(swStTvmCheckDetail.getRevenueTime());
                    swStInputCashboxUninstalleds.add(cashBox);
                }
            }
            SwStTvmCheckDetailDTO tvmDto = queryDetailsByid(swStTvmCheckDetail.getId(),"1");
            tvmDto.setSwStTvmCheckDetail(swStTvmCheckDetail);
            tvmDto.setSwStTvmCheckDetailWastes(swStTvmCheckDetailWastes);
            updateSwStTvmCheckDetail(tvmDto);
            tvmCode = swStTvmCheckDetailWastes.get(0).getTvmCode();

        }
        if (flag) {
            updateById(swStTvmCheckDetail);
        }
        if (StringUtils.isNotBlank(tvmCode)) {
            swStTvmCheckDetail.setTvmCode(tvmCode);
            updateById(swStTvmCheckDetail);
        }

        if (CollectionUtil.isNotEmpty(swStInputCashboxUninstalleds)) {
            swStInputCashboxUninstalledService.saveBatch(swStInputCashboxUninstalleds);
        }
        return swStTvmCheckDetail.getId();
    }

    /**
     * 增加提醒功能：当录入同一结算周期范围内相同TVM编号两条数据时增加提醒功能，禁止录入
     * @param swStTvmCheckDetail
     * @param revenueTime
     * @return
     * @throws SQLException
     */
    private List<Map<String,Object>> getTvmListMap(SwStTvmCheckDetail swStTvmCheckDetail, LocalDate revenueTime) throws SQLException {
        //比如7天结算周期的TVM，当在这个周期，同时录入多条TVM008的钱箱清点记录时，进行提示，不允许录入多次。
        //就是一个TVM在这个7天的结算周期内一种钱箱只允许录入一次。
        //根据收益日期如果查不到最新周期的数据，再根据收益日期到历史规则记录表内查找历史周期规则
        String localDateToString = DateUtilStm.localDateToString(revenueTime,"yyyy-MM-dd");
        //从结算周期设置表内获取日期范围
        String sqlDateRange="    select\n" +
                "    DATE_FORMAT(date_add(a.END_TIME,interval 1 second),'%Y-%m-%d') BEGIN_TIME,\n" +
                "    DATE_FORMAT(date_add(a.END_TIME,interval (ifnull(b.settlement_term,1)-1) day),'%Y-%m-%d') " +
                "END_TIME\n" +
                "    from SW_CK_DATA_SUBMIT a\n" +
                "     left join sw_pm_long_period_settlement b on  a.LINE_CODE = b.LINE_CODE  and a.STATION_CODE = b" +
                ".STATION_CODE\n" +
                "    and b.DEL_FLAG = '0' and b.STATUS = '1'\n" +
                "     where  a.LINE_CODE = '"+swStTvmCheckDetail.getLineCode()+"'\n" +
                "     and a.STATION_CODE = '"+swStTvmCheckDetail.getStationCode()+"'\n" +
                "    and '"+localDateToString+"' BETWEEN  DATE_FORMAT(date_add(a.END_TIME,interval 1 second),'%Y-%m-%d')\n" +
                "    and DATE_FORMAT(date_add(a.END_TIME,interval (ifnull(b.settlement_term,1)-1) day),'%Y-%m-%d')";
        List<Map<String,Object>> dateRange = JdbcUtil.exeSqlQuery(sqlDateRange);
        //Map<String,Object> dateRange = this.baseMapper.getDateRange(swStTvmCheckDetail.getLineCode(),swStTvmCheckDetail.getStationCode(),localDateToString);
        if(CollectionUtil.isEmpty(dateRange) || dateRange.size()<0){
            //如果上面的SQL不存在，根据收入日期，从日志表内获取结算日期范围
            //Map<String,Object> dateRangeLog = this.baseMapper.getDateRangeLog(swStTvmCheckDetail.getLineCode(),swStTvmCheckDetail.getStationCode(),localDateToString);
            String sqlDateRangeLog="    select DATE_FORMAT(begin_time,'%Y-%m-%d') BEGIN_TIME,\n" +
                    "           DATE_FORMAT(DATE_ADD(end_time,interval -1 day),'%Y-%m-%d')  END_TIME\n" +
                    "     from sw_ck_data_submit_log\n" +
                    "     where  LINE_CODE = '"+swStTvmCheckDetail.getLineCode()+"'\n" +
                    "     and STATION_CODE = '"+swStTvmCheckDetail.getStationCode()+"'\n" +
                    "    and '"+localDateToString+"' between DATE_FORMAT(begin_time,'%Y-%m-%d') and DATE_FORMAT(DATE_ADD(end_time,interval -1 day),'%Y-%m-%d')\n" +
                    "    order by submit_time desc limit 0,1";
            List<Map<String,Object>> dateRangeLog = JdbcUtil.exeSqlQuery(sqlDateRangeLog);
            if(CollectionUtil.isNotEmpty(dateRangeLog) && dateRangeLog.size()>0 && dateRangeLog != null){
                return dateRangeLog;
            }
            return null;

        }else {
            return dateRange;
        }
    }

    /**
     * 根据结算周期范围查主表
     * @param swStTvmCheckDetail
     * @param tvmListMap
     * @param tvmCode
     * @return
     */
    private List<SwStTvmCheckDetail> getTvmList(SwStTvmCheckDetail swStTvmCheckDetail, List<Map<String, Object>> tvmListMap, String tvmCode) {
        List<SwStTvmCheckDetail> tvmList =
                list(new QueryWrapper<SwStTvmCheckDetail>().lambda().eq(SwStTvmCheckDetail::getLineCode,
                        swStTvmCheckDetail.getLineCode())
                        .eq(SwStTvmCheckDetail::getStationCode, swStTvmCheckDetail.getStationCode())
                        .eq(SwStTvmCheckDetail::getTvmCode, tvmCode).between(SwStTvmCheckDetail::getRevenueTime,
                                tvmListMap.get(0).get("BEGIN_TIME"), tvmListMap.get(0).get("END_TIME")).eq(SwStTvmCheckDetail::getDelFlag,"0"));
        return tvmList;
    }
    /**
     * 查询主表存不存在
     *
     * @param swStTvmCheckDetail
     * @param revenueTime
     * @param tvmCode
     * @return
     */
    private SwStTvmCheckDetail getMainTable(SwStTvmCheckDetail swStTvmCheckDetail, LocalDate revenueTime, String tvmCode) {
        return getOne(new QueryWrapper<SwStTvmCheckDetail>().lambda().eq(SwStTvmCheckDetail::getLineCode, swStTvmCheckDetail.getLineCode())
                .eq(SwStTvmCheckDetail::getStationCode, swStTvmCheckDetail.getStationCode())
                .eq(SwStTvmCheckDetail::getTvmCode, tvmCode).eq(SwStTvmCheckDetail::getRevenueTime, revenueTime));
    }

    @Override
    public boolean confirmBatch(List<Integer> ids) {
        Collection<SwStTvmCheckDetail> swStTvmCheckDetails = listByIds(ids);
        for (SwStTvmCheckDetail swStTvmCheckDetail : swStTvmCheckDetails) {
            if(CommonConstants.UN_CONFIRM.equals(swStTvmCheckDetail.getConfirmStatus())){
                swStTvmCheckDetail.setConfirmStatus(CommonConstants.CONFIRM);
            }
        }
        return updateBatchById(swStTvmCheckDetails);
    }

    @Override
    @Transactional
    public boolean saveCheckDetailDataEntryLog(SwStTvmCheckDetailDTO swStTvmCheckDetailDTO, Integer id) {
        PigxUser user = SecurityUtils.getUser();
        SwStTvmCheckDetail swStTvmCheckDetail = swStTvmCheckDetailDTO.getSwStTvmCheckDetail();
        if(swStTvmCheckDetail != null ){
            SwStTvmCheckDetail swStTvmCheckDetailOld = getById(swStTvmCheckDetail.getId());
            //Integer mainId = 0;
            //报表差错修改开关为“1”打开状态下的时候添加到记录表（先添加主表）
            if(swStTvmCheckDetailOld != null && "1".equals(swStTvmCheckDetailOld.getReportModifyStatus())) {
//                boolean isTure = true;
//                if(swStTvmCheckDetail.getCheckPersonTwoJopNo().equals(swStTvmCheckDetailOld.getCheckPersonTwoJopNo())
//                        && swStTvmCheckDetail.getRemark().equals(swStTvmCheckDetailOld.getRemark())
//                        && swStTvmCheckDetail.getCheckTime().equals(swStTvmCheckDetailOld.getCheckTime())){
//                    isTure = false;
//                }
//                if(isTure) {
//                }
                swStTvmCheckDetailOld.setEntryUpdateJobNo(user.getUserCode());
                swStTvmCheckDetailOld.setEntryUpdateJobName(user.getNikeName());
                swStTvmCheckDetailOld.setEntryUpdateTime(new Date());
                SwStmStationDataEntryLog swStmStationDataEntryLog = new SwStmStationDataEntryLog();
                swStmStationDataEntryLog.setRelationId(swStTvmCheckDetailOld.getId());
                swStmStationDataEntryLog.setLogTableName(StmTableCommon.SW_ST_TVM_CHECK_DETAIL);
                swStmStationDataEntryLog.setLogInfo(JSONObject.toJSONString(swStTvmCheckDetailOld));
                swStmStationDataEntryLog.setUpdateJobNo(user.getUserCode());
                swStmStationDataEntryLog.setUpdateJobName(user.getNikeName());
                swStmStationDataEntryLog.setUpdateTime(new Date());
                swStmStationDataEntryLogService.save(swStmStationDataEntryLog);
                Integer mainId = swStmStationDataEntryLog.getId();

                List<SwStmStationDataEntryLog> list = new ArrayList<>();
                List<SwStTvmCheckDetailCoinChange> swStTvmCheckDetailCoinChanges = swStTvmCheckDetailDTO.getSwStTvmCheckDetailCoinChanges();
                if (CollectionUtil.isNotEmpty(swStTvmCheckDetailCoinChanges)) {
                    //报表差错修改开关为“1”打开状态下的时候添加到记录表（先添加主表）
                    if("1".equals(swStTvmCheckDetailOld.getReportModifyStatus())) {
                        //修改之前添加记录表（再添加子表）
                        List<SwStTvmCheckDetailCoinChange> swStTvmCheckDetailCoinChangeList = swStTvmCheckDetailCoinChangeService.list(
                                Wrappers.<SwStTvmCheckDetailCoinChange>lambdaQuery()
                                        .eq(SwStTvmCheckDetailCoinChange::getRelationId, swStTvmCheckDetailOld.getId())
                                        //.eq(SwStTvmCheckDetailCoinChange::getReportModifyStatus, "1")
                                        .eq(SwStTvmCheckDetailCoinChange::getDelFlag,0));

                        if(CollectionUtil.isNotEmpty(swStTvmCheckDetailCoinChangeList)){
                            swStTvmCheckDetailCoinChangeList.stream().forEach(detailCoinChange -> {
                                detailCoinChange.setEntryUpdateJobNo(user.getUserCode());
                                detailCoinChange.setEntryUpdateJobName(user.getNikeName());
                                detailCoinChange.setEntryUpdateTime(new Date());

                                SwStmStationDataEntryLog swStmStationDataEntryLogChild = new SwStmStationDataEntryLog();
                                swStmStationDataEntryLogChild.setRelationId(swStTvmCheckDetailOld.getId());
                                swStmStationDataEntryLogChild.setLogTableName(StmTableCommon.SW_ST_TVM_CHECK_DETAIL_COIN_CHANGE);
                                swStmStationDataEntryLogChild.setMainId(mainId);//记录表id
                                swStmStationDataEntryLogChild.setLogInfo(JSONObject.toJSONString(detailCoinChange));
                                swStmStationDataEntryLogChild.setUpdateJobNo(user.getUserCode());
                                swStmStationDataEntryLogChild.setUpdateJobName(user.getNikeName());
                                swStmStationDataEntryLogChild.setUpdateTime(new Date());
                                list.add(swStmStationDataEntryLogChild);
                            });
                        }
                    }
                }
                List<SwStTvmCheckDetailCoin> swStTvmCheckDetailCoins = swStTvmCheckDetailDTO.getSwStTvmCheckDetailCoins();
                if (CollectionUtil.isNotEmpty(swStTvmCheckDetailCoins)) {
                    //报表差错修改开关为“1”打开状态下的时候添加到记录表（先添加主表）
                    if("1".equals(swStTvmCheckDetailOld.getReportModifyStatus())) {
                        //修改之前添加记录表（再添加子表）
                        List<SwStTvmCheckDetailCoin> swStTvmCheckDetailCoinList = swStTvmCheckDetailCoinService.list(
                                Wrappers.<SwStTvmCheckDetailCoin>lambdaQuery()
                                        .eq(SwStTvmCheckDetailCoin::getRelationId, swStTvmCheckDetailOld.getId())
                                        //.eq(SwStTvmCheckDetailCoin::getReportModifyStatus, "1")
                                        .eq(SwStTvmCheckDetailCoin::getDelFlag,0));

                        if(CollectionUtil.isNotEmpty(swStTvmCheckDetailCoinList)){
                            swStTvmCheckDetailCoinList.stream().forEach(detailCoin -> {
                                detailCoin.setEntryUpdateJobNo(user.getUserCode());
                                detailCoin.setEntryUpdateJobName(user.getNikeName());
                                detailCoin.setEntryUpdateTime(new Date());

                                SwStmStationDataEntryLog swStmStationDataEntryLogChild = new SwStmStationDataEntryLog();
                                swStmStationDataEntryLogChild.setRelationId(swStTvmCheckDetailOld.getId());
                                swStmStationDataEntryLogChild.setLogTableName(StmTableCommon.SW_ST_TVM_CHECK_DETAIL_COIN);
                                swStmStationDataEntryLogChild.setMainId(mainId);//记录表id
                                swStmStationDataEntryLogChild.setLogInfo(JSONObject.toJSONString(detailCoin));
                                swStmStationDataEntryLogChild.setUpdateJobNo(user.getUserCode());
                                swStmStationDataEntryLogChild.setUpdateJobName(user.getNikeName());
                                swStmStationDataEntryLogChild.setUpdateTime(new Date());
                                list.add(swStmStationDataEntryLogChild);
                            });
                        }
                    }
                }
                List<SwStTvmCheckDetailPaper> swStTvmCheckDetailPapers = swStTvmCheckDetailDTO.getSwStTvmCheckDetailPapers();
                if (CollectionUtil.isNotEmpty(swStTvmCheckDetailPapers)) {
                    //报表差错修改开关为“1”打开状态下的时候添加到记录表（先添加主表）
                    if("1".equals(swStTvmCheckDetailOld.getReportModifyStatus())) {
                        //修改之前添加记录表（再添加子表）
                        List<SwStTvmCheckDetailPaper> swStTvmCheckDetailPaperList = swStTvmCheckDetailPaperService.list(
                                Wrappers.<SwStTvmCheckDetailPaper>lambdaQuery()
                                        .eq(SwStTvmCheckDetailPaper::getRelationId, swStTvmCheckDetailOld.getId())
                                        //.eq(SwStTvmCheckDetailPaper::getReportModifyStatus, "1")
                                        .eq(SwStTvmCheckDetailPaper::getDelFlag,0));

                        if(CollectionUtil.isNotEmpty(swStTvmCheckDetailPaperList)){
                            swStTvmCheckDetailPaperList.stream().forEach(detailPaper -> {
                                detailPaper.setEntryUpdateJobNo(user.getUserCode());
                                detailPaper.setEntryUpdateJobName(user.getNikeName());
                                detailPaper.setEntryUpdateTime(new Date());

                                SwStmStationDataEntryLog swStmStationDataEntryLogChild = new SwStmStationDataEntryLog();
                                swStmStationDataEntryLogChild.setRelationId(swStTvmCheckDetailOld.getId());
                                swStmStationDataEntryLogChild.setLogTableName(StmTableCommon.SW_ST_TVM_CHECK_DETAIL_PAPER);
                                swStmStationDataEntryLogChild.setMainId(mainId);//记录表id
                                swStmStationDataEntryLogChild.setLogInfo(JSONObject.toJSONString(detailPaper));
                                swStmStationDataEntryLogChild.setUpdateJobNo(user.getUserCode());
                                swStmStationDataEntryLogChild.setUpdateJobName(user.getNikeName());
                                swStmStationDataEntryLogChild.setUpdateTime(new Date());
                                list.add(swStmStationDataEntryLogChild);
                            });
                        }

                    }

                }
                List<SwStTvmCheckDetailPaperChange> swStTvmCheckDetailPaperChanges = swStTvmCheckDetailDTO.getSwStTvmCheckDetailPaperChanges();
                if (CollectionUtil.isNotEmpty(swStTvmCheckDetailPaperChanges)) {
                    //报表差错修改开关为“1”打开状态下的时候添加到记录表（先添加主表）
                    if("1".equals(swStTvmCheckDetailOld.getReportModifyStatus())) {
                        //修改之前添加记录表（再添加子表）
                        List<SwStTvmCheckDetailPaperChange> swStTvmCheckDetailPaperChangeList = swStTvmCheckDetailPaperChangeService.list(
                                Wrappers.<SwStTvmCheckDetailPaperChange>lambdaQuery()
                                        .eq(SwStTvmCheckDetailPaperChange::getRelationId, swStTvmCheckDetailOld.getId())
                                        //.eq(SwStTvmCheckDetailPaperChange::getReportModifyStatus, "1")
                                        .eq(SwStTvmCheckDetailPaperChange::getDelFlag,0));

                        if(CollectionUtil.isNotEmpty(swStTvmCheckDetailPaperChangeList)){
                            swStTvmCheckDetailPaperChangeList.stream().forEach(detailPaperChange -> {
                                detailPaperChange.setEntryUpdateJobNo(user.getUserCode());
                                detailPaperChange.setEntryUpdateJobName(user.getNikeName());
                                detailPaperChange.setEntryUpdateTime(new Date());

                                SwStmStationDataEntryLog swStmStationDataEntryLogChild = new SwStmStationDataEntryLog();
                                swStmStationDataEntryLogChild.setRelationId(swStTvmCheckDetailOld.getId());
                                swStmStationDataEntryLogChild.setLogTableName(StmTableCommon.SW_ST_TVM_CHECK_DETAIL_PAPER_CHANGE);
                                swStmStationDataEntryLogChild.setMainId(mainId);//记录表id
                                swStmStationDataEntryLogChild.setLogInfo(JSONObject.toJSONString(detailPaperChange));
                                swStmStationDataEntryLogChild.setUpdateJobNo(user.getUserCode());
                                swStmStationDataEntryLogChild.setUpdateJobName(user.getNikeName());
                                swStmStationDataEntryLogChild.setUpdateTime(new Date());
                                list.add(swStmStationDataEntryLogChild);
                            });
                        }

                    }

                }

                List<SwStTvmCheckDetailWaste> swStTvmCheckDetailWastes = swStTvmCheckDetailDTO.getSwStTvmCheckDetailWastes();
                if (CollectionUtil.isNotEmpty(swStTvmCheckDetailWastes)) {
                    //报表差错修改开关为“1”打开状态下的时候添加到记录表（先添加主表）
                    if("1".equals(swStTvmCheckDetailOld.getReportModifyStatus())) {
                        //修改之前添加记录表（再添加子表）
                        List<SwStTvmCheckDetailWaste> swStTvmCheckDetailWasteList = stTvmCheckDetailWasteService.list(
                                Wrappers.<SwStTvmCheckDetailWaste>lambdaQuery()
                                        .eq(SwStTvmCheckDetailWaste::getRelationId, swStTvmCheckDetailOld.getId())
                                        //.eq(SwStTvmCheckDetailWaste::getReportModifyStatus, "1")
                                        .eq(SwStTvmCheckDetailWaste::getDelFlag,0));

                        if(CollectionUtil.isNotEmpty(swStTvmCheckDetailWasteList)){
                            swStTvmCheckDetailWasteList.stream().forEach(detailWaste -> {
                                detailWaste.setEntryUpdateJobNo(user.getUserCode());
                                detailWaste.setEntryUpdateJobName(user.getNikeName());
                                detailWaste.setEntryUpdateTime(new Date());

                                SwStmStationDataEntryLog swStmStationDataEntryLogChild = new SwStmStationDataEntryLog();
                                swStmStationDataEntryLogChild.setRelationId(swStTvmCheckDetailOld.getId());
                                swStmStationDataEntryLogChild.setLogTableName(StmTableCommon.SW_ST_TVM_CHECK_DETAIL_WASTE);
                                swStmStationDataEntryLogChild.setMainId(mainId);//记录表id
                                swStmStationDataEntryLogChild.setLogInfo(JSONObject.toJSONString(detailWaste));
                                swStmStationDataEntryLogChild.setUpdateJobNo(user.getUserCode());
                                swStmStationDataEntryLogChild.setUpdateJobName(user.getNikeName());
                                swStmStationDataEntryLogChild.setUpdateTime(new Date());
                                list.add(swStmStationDataEntryLogChild);
                            });
                        }

                    }
                }
                swStmStationDataEntryLogService.saveBatch(list);
            }
        }
        return true;
    }

}
